package orm

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"api/system/helper"
	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func getDb(cfg *Conf) *sql.DB {
	if db != nil {
		return db
	}

	if err := cfg.Check(); err != nil {
		helper.Dry(err.Error())
	}
	dsn := cfg.String()

	dbConn, err := sql.Open(strings.ToLower(cfg.Type), dsn)
	if err != nil {
		helper.Dry(err.Error())
	}

	dbConn.SetConnMaxLifetime(time.Duration(cfg.MaxLifetime))
	dbConn.SetConnMaxIdleTime(time.Duration(cfg.MaxIdleTime))
	dbConn.SetMaxOpenConns(cfg.MaxOpenConn)
	dbConn.SetMaxIdleConns(cfg.MaxIdleConn)

	if err := dbConn.Ping(); err != nil {
		helper.Dry("打开数据库连接失败，原因：" + err.Error())
	}

	return dbConn
}

type TableInfo struct {
	Ctype     string
	Length    sql.NullInt32
	IntLength sql.NullInt32
	Column    string
	Comment   string
}

func Table(name string, cfg *Conf) ([]TableInfo, error) {
	db = getDb(cfg)
	prefix := cfg.Prefix
	dbname := cfg.DataBase

	sqlStr := fmt.Sprintf(`SELECT
		DATA_TYPE as 'ctype',
		CHARACTER_MAXIMUM_LENGTH as 'length',
		NUMERIC_PRECISION as 'intlength',
    	COLUMN_NAME as 'column',
    	COLUMN_COMMENT as 'comment'
	FROM
    	INFORMATION_SCHEMA.COLUMNS 
	WHERE TABLE_SCHEMA = '%v' AND TABLE_NAME = '%v'`, dbname, prefix+name)

	var result []TableInfo

	rows, err := db.Query(sqlStr)
	if err != nil && err != sql.ErrNoRows {
		return nil, err
	}

	for rows.Next() {
		var ctype, column, comment string
		var length, intlength sql.NullInt32

		if err := rows.Scan(&ctype, &length, &intlength, &column, &comment); err != nil {
			return nil, err
		}

		result = append(result, TableInfo{
			Ctype:     ctype,
			Length:    length,
			IntLength: intlength,
			Column:    column,
			Comment:   comment,
		})
	}

	defer rows.Close()

	return result, nil
}
